﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using Update;
using ICSharpCode.SharpZipLib.Zip;

namespace autoUpdate
{
    public partial class Form1 : Form
    {
        [DllImport("zipfile.dll")]
        public static extern int MyZip_ExtractFileAll(string zipfile, string pathname);
        public Form1()
        {
            InitializeComponent();
            //清除之前下载来的rar文件
            if (File.Exists(Application.StartupPath + "\\Update_autoUpdate.zip"))
            {
                try
                {
                    File.Delete(Application.StartupPath + "\\Update_autoUpdate.zip");
                }
                catch (Exception)
                {


                }

            }
            if (Directory.Exists(Application.StartupPath + "\\autoupload"))
            {
                try
                {
                    Directory.Delete(Application.StartupPath + "\\autoupload", true);
                }
                catch (Exception)
                {


                }
            }

            //检查服务端是否有新版本程序
            checkUpdate();
            timer1.Enabled = true;
        }
        SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "包覆门");
        public void checkUpdate()
        {

            app.UpdateFinish += new UpdateState(app_UpdateFinish);
            try
            {
                if (app.IsUpdate)
                {
                    app.Update();
                }
                else
                {
                    MessageBox.Show("未检测到新版本!");
                    Application.Exit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void app_UpdateFinish()
        {   
            //解压下载后的文件
            string path = app.FinalZipName;
            if (File.Exists(path))
            {
                //后改的 先解压滤波zip植入ini然后再重新压缩
                string dirEcgPath = Application.StartupPath + "\\" + "autoupload";
                if (!Directory.Exists(dirEcgPath))
                {
                    Directory.CreateDirectory(dirEcgPath);
                }
                //开始解压压缩包
               // MyZip_ExtractFileAll(path, dirEcgPath);
                UnZipDir(path, dirEcgPath, true);
                try
                {
                    //复制新文件替换旧文件
                    //DirectoryInfo TheFolder = new DirectoryInfo(dirEcgPath);
                    //foreach (FileInfo NextFile in TheFolder.GetFiles())
                    //foreach (FileInfo NextFile in TheFolder.GetFileSystemInfos())
                    //{
                    //    File.Copy(NextFile.FullName, Application.StartupPath + "\\program\\" + NextFile.Name, true);
                    //}
                    CopyDirectory(dirEcgPath, Application.StartupPath + "\\program");

                    Directory.Delete(dirEcgPath, true);
                    File.Delete(path);
                    //覆盖完成 重新启动程序
                    path = Application.StartupPath + "\\program";
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo.FileName = "包覆门.exe";
                    process.StartInfo.WorkingDirectory = path;//要掉用得exe路径例如:"C:\windows";               
                    process.StartInfo.CreateNoWindow = true;
                    process.Start();

                    Application.Exit();
                }
                catch (Exception)
                {
                    MessageBox.Show("请关闭系统在执行更新操作!");
                    Application.Exit();
                }
            }
        }
        //复制
        public static void CopyDirectory(string srcPath, string destPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下（不包含子目录）的文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)     //判断是否文件夹
                    {
                        if (!Directory.Exists(destPath + "\\" + i.Name))
                        {
                            Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
                        }
                        CopyDirectory(i.FullName, destPath + "\\" + i.Name);    //递归调用复制子文件夹
                    }
                    else
                    {
                        File.Copy(i.FullName, destPath + "\\" + i.Name, true);      //不是文件夹即复制文件，true表示可以覆盖同名文件
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("请关闭系统在执行更新操作!");
                Application.Exit();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label2.Text = "下载文件进度:" + CommonDownLoad.CommonMethod.autostep.ToString() + "%";
            this.progressBar1.Value = CommonDownLoad.CommonMethod.autostep;
            if (CommonDownLoad.CommonMethod.autostep == 100)
            {
                //this.progressBar1.Value = this.progressBar1.Maximum;
                timer1.Enabled = false;
            }
        }

        /// summary; 
        ///  解压缩一个  zip  文件。 
        /// summary
        /// param  name="zipFileName";要解压的  zip  文件。   
        /// ///  ;param  name="extractLocation";zip  文件的解压目录。;/param;  
        /// ///  ;param  name="password";zip  文件的密码。;/param;      
        /// ///  ;param  name="overWrite";是否覆盖已存在的文件。;/param;  
        public void UnZipDir(string zipFileName, string extractLocation, bool overWrite)
        {
            #region  实现
            string myExtractLocation = extractLocation;
            if (myExtractLocation == "")
                myExtractLocation = Directory.GetCurrentDirectory();
            if (!myExtractLocation.EndsWith(@"\"))
                myExtractLocation = myExtractLocation + @"\";

            ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName));
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = "";
                string pathToZip = "";
                pathToZip = theEntry.Name;
                if (pathToZip != "")
                    directoryName = System.IO.Path.GetDirectoryName(pathToZip) + @"\";
                string fileName = System.IO.Path.GetFileName(pathToZip);
                Directory.CreateDirectory(myExtractLocation + directoryName);
                if (fileName != "")
                {
                    try
                    {
                        if ((File.Exists(myExtractLocation + directoryName + fileName) && overWrite) || (!File.Exists(myExtractLocation + directoryName + fileName)))
                        {
                            FileStream streamWriter = File.Create(myExtractLocation + directoryName + fileName);
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                    streamWriter.Write(data, 0, size);
                                else
                                    break;
                            }
                            streamWriter.Close();
                        }
                    }
                    catch (ZipException ex)
                    {
                        FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "log.txt", FileMode.OpenOrCreate, FileAccess.Write);
                        StreamWriter sw = new StreamWriter(fs);
                        sw.WriteLine(ex.Message);
                    }
                }
            }
            s.Close();
            #endregion
        }
    }
}
